import { Hono } from "hono";
import getHtml from "../../indexTemplate.ts";
import activeClients from "../utils/activeClients.ts";
import { getConnInfo } from 'hono/deno'
const isProd = Deno.args[0] === 'prod';

const setClientRoute = async (app: Hono) => {
    if (isProd) {
        console.log('%c生产环境，不编译静态文件', 'color: blue;');
    } else {
        // 编译静态文件
        await Deno.bundle({
            entrypoints: ['./client/App.tsx'],
            outputPath: './client/App.js',
        })
        console.log('%c静态文件编译完成', 'color: green;');
    }

    app.get('/client/App.js', (c) => {
        const appJs = Deno.readFileSync(new URL("../../client/App.js", import.meta.url));      
        return c.body(appJs, 200, {
            'Content-Type': 'application/javascript',
        });
    })

    app.get('/client/App.css', (c) => {
        const appCss = Deno.readFileSync(new URL("../../client/App.css", import.meta.url));      
        return c.body(appCss, 200, {
            'Content-Type': 'text/css',
        });
    })

    app.get('/favicon.ico', (c) => {
        const appFavicon = Deno.readFileSync(new URL("../../client/favicon.ico", import.meta.url));      
        return c.body(appFavicon, 200, {
            'Content-Type': 'image/x-icon',
        });
    })

    app.get('/', (c) => {
        const curIp = getConnInfo(c).remote.address;
        activeClients.addClient(curIp!);
        const html = getHtml();
        return c.html(html);
    })
}

export default setClientRoute;